package com.macro.mall.portal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.exception.ApiException;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.service.RedisService;
import com.macro.mall.common.util.DateUtil;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.component.MessageSender;
import com.macro.mall.portal.dao.*;
import com.macro.mall.portal.domain.*;
import com.macro.mall.portal.dto.OmsReturnApplyDto;
import com.macro.mall.portal.dto.PmsProductDto;
import com.macro.mall.portal.service.*;
import com.macro.mall.portal.service.activityImpl.ActivityImpl;
import com.macro.mall.wx.domain.WxPayDTO;
import com.macro.mall.wx.domain.WxRefundDTO;
import com.macro.mall.wx.sdk.WxMyConfig;
import com.macro.mall.wx.service.RefundService;
import com.macro.mall.wx.service.WxPayService;
import com.quyum.mall.market.config.RedisKey;
import com.quyum.mall.market.entity.MarketSmsGroupBuy;
import com.quyum.mall.market.entity.MarketSmsGroupBuyOrder;
import com.quyum.mall.market.entity.MarketSmsRound;
import com.quyum.mall.market.entity.MarketSmsRoundProduct;
import com.quyum.mall.market.example.MarketSmsGroupBuyOrderExample;
import com.quyum.mall.market.mapper.MarketSmsGroupBuyMapper;
import com.quyum.mall.market.mapper.MarketSmsGroupBuyOrderMapper;
import com.quyum.mall.market.mapper.MarketSmsRoundProductMapper;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 前台订单管理Service
 * Created by macro on 2018/8/30.
 */
@Service
public class OmsPortalOrderServiceImpl implements OmsPortalOrderService {
    @Value("${redis.key.orderId}")
    private String REDIS_KEY_ORDER_ID;
    @Value("${redis.database}")
    private String REDIS_DATABASE;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private OmsCartItemService cartItemService;
    @Autowired
    private UmsMemberReceiveAddressService memberReceiveAddressService;
    @Autowired
    private UmsMemberCouponService memberCouponService;
    @Autowired
    private UmsIntegrationConsumeSettingMapper integrationConsumeSettingMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private SmsCouponHistoryDao couponHistoryDao;
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private PortalOrderItemDao orderItemDao;
    @Autowired
    private SmsCouponHistoryMapper couponHistoryMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PortalOrderDao portalOrderDao;
    @Autowired
    private OmsOrderSettingMapper orderSettingMapper;
    @Autowired
    private OmsOrderItemMapper orderItemMapper;
    @Autowired
    private MessageSender messageSender;
    @Autowired
    private UmsStoreCacheService umsStoreCacheService;
    @Autowired
    private OmsPromotionService promotionService;
    @Autowired
    private OmsAgentSendMapper omsAgentSendMapper;
    @Autowired
    private UmsIntegrationChangeHistoryMapper integrationMapper;
    @Autowired
    private PmsCombinedProductMapper pmsCombinedProductMapper;
    @Autowired
    private PmsCombinedProductDao pmsCombinedProductDao;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private PmsStockDao pmsStockDao;
    @Autowired
    private OmsOrderReturnApplyMapper returnApplyMapper;
    @Autowired
    private OmsOrderSettingMapper settingMapper;
    @Autowired
    private PortalSkuStockDao skuStockDao;
    @Autowired
    private PmsSkuStockMapper pmsSkuStockMapper;
    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private ActivityImpl activity;
    @Autowired
    private RefundService refundService;
    @Autowired
    private PmsMemberPriceMapper memberPriceMapper;
    @Autowired
    private MarketSmsGroupBuyMapper smsGroupBuyMapper;
    @Autowired
    private MarketSmsGroupBuyOrderMapper smsGroupBuyOrderMapper;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private SmsCouponMapper couponMapper;
    @Autowired
    private PmsProductMapper productMapper;

    @Override
    public ConfirmOrderResult generateConfirmOrder(String cartIds) {
        List<Long> cartList = new ArrayList<>();
        if (cartIds.contains(",")) {
            String[] split = cartIds.split(",");
            for (int i = 0; i < split.length; i++) {
                Long l = Long.parseLong(split[i]);
                cartList.add(l);
            }
        } else {
            cartList.add(Long.parseLong(cartIds));
        }

        //获取购物车信息
        UmsMember currentMember = memberService.getCurrentMember();
        List<CartPromotionItem> cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(), cartList, currentMember.getStoreId());
        return this.getConfirmOrderResult(cartPromotionItemList);
    }

    @Override
    public ConfirmOrderResult generateConfirmOrderOrderItemDetails(Long skuId, Integer quantity) {
        //获取购物车信息
        UmsMember currentMember = memberService.getCurrentMember();
        List<OmsCartItem> list = new ArrayList<>();
        list.add(this.getOmsCartItem(skuId, quantity, currentMember));
        //获取购物车及优惠信息
        List<CartPromotionItem> cartPromotionItemList = this.promotionService.calcCartPromotion(currentMember.getId(), list, currentMember.getStoreId());
        return this.getConfirmOrderResult(cartPromotionItemList);
    }

    /**
     * 确认订单的主方法
     *
     * @param cartPromotionItemList
     * @return
     * @author zhouboyu
     * 4@Date 2020年9月10日
     */
    private ConfirmOrderResult getConfirmOrderResult(List<CartPromotionItem> cartPromotionItemList) {
        ConfirmOrderResult result = new ConfirmOrderResult();
        result.setCartPromotionItemList(cartPromotionItemList);
        //获取用户可用优惠券列表
//        List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, this.memberService.getCurrentMember().getId(), 1);
//        result.setCouponHistoryDetailList(null);
        List<UmsMemberReceiveAddress> memberReceiveAddressList = new ArrayList<>();
        UmsMemberReceiveAddress aDefault = this.memberReceiveAddressService.getDefault();
        memberReceiveAddressList.add(aDefault);
        result.setMemberReceiveAddressList(memberReceiveAddressList);
//        //获取用户积分
//        result.setMemberIntegration(currentMember.getIntegration());
//        //获取积分使用规则
//        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
//        result.setIntegrationConsumeSetting(integrationConsumeSetting);
        //计算总金额、活动优惠、应付金额
        ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(cartPromotionItemList);
        result.setCalcAmount(calcAmount);
        return result;
    }

    @Override
    public Long generateOrder(OrderParam orderParam) {
        UmsMember currentMember = this.memberService.getCurrentMember();
        List<CartPromotionItem> cartPromotionItemList = this.cartItemService.listPromotion(currentMember.getId(), orderParam.getCartIds(), currentMember.getStoreId());
        return this.getStringObjectMap(currentMember, orderParam, cartPromotionItemList, 1);
    }

    @Override
    public Long generateOrderItemDetails(OrderParam orderParam) {
        UmsMember currentMember = this.memberService.getCurrentMember();
        List<OmsCartItem> list = new ArrayList<>();
        Long skuId = orderParam.getSkuId();
        Integer quantity = orderParam.getQuantity().intValue();
        list.add(this.getOmsCartItem(skuId, quantity, currentMember));
        //获取购物车及优惠信息
        List<CartPromotionItem> cartPromotionItemList = this.promotionService.calcCartPromotion(currentMember.getId(), list, currentMember.getStoreId());
        return this.getStringObjectMap(currentMember, orderParam, cartPromotionItemList, 0); }

    /**
     * 通过skuId和数量组装购物车
     *
     * @param skuId
     * @param quantity
     * @param currentMember
     * @return
     * @author zhouboyu
     * @Date 2020年9月10日
     */
    @Override
    public OmsCartItem getOmsCartItem(Long skuId, Integer quantity, UmsMember currentMember) {
        PmsProductDto pmsProductDto = this.orderItemDao.getPmsProductDtoBySkuId(skuId);
        PmsSkuStock pmsSkuStock = pmsProductDto.getPmsSkuStock();
        OmsCartItem omsCartItem = new OmsCartItem();
        omsCartItem.setId(skuId);
        omsCartItem.setModifyDate(new Date());
        omsCartItem.setDeleteStatus(0);
        omsCartItem.setCreateDate(new Date());
        omsCartItem.setMemberId(currentMember.getId());
        omsCartItem.setMemberNickname(currentMember.getNickname());
        omsCartItem.setProductAttr(pmsProductDto.getPmsSkuStock().getSpData());
        omsCartItem.setProductBrand(pmsProductDto.getBrandName());
        Integer memberLevel = currentMember.getMemberLevel();
        omsCartItem.setPrice(pmsSkuStock.getPrice());
        omsCartItem.setProductSkuCode(pmsSkuStock.getSkuCode());
        omsCartItem.setProductCategoryId(pmsProductDto.getProductCategoryId());
        omsCartItem.setProductName(pmsProductDto.getName());
        omsCartItem.setProductId(pmsProductDto.getId());
        omsCartItem.setProductPic(pmsProductDto.getPic());
        omsCartItem.setProductSkuId(skuId);
        omsCartItem.setProductSn(pmsProductDto.getProductSn());
        omsCartItem.setProductSubTitle(pmsProductDto.getSubTitle());
        omsCartItem.setQuantity(quantity);
        return omsCartItem;
    }

    /**
     * 确认订单主方法
     *
     * @param currentMember
     * @param orderParam
     * @param cartPromotionItemList
     * @return
     * @author zhouboyu
     * @Date 2020年9月9日
     */
    @Transactional
    public Long getStringObjectMap(UmsMember currentMember, OrderParam orderParam, List<CartPromotionItem> cartPromotionItemList, Integer type) {
        UmsStore store = this.umsStoreCacheService.getStore(orderParam.getStoreId());
        List<OmsOrderItem> orderItemList = new ArrayList<>();
        //订单商品类型
        Integer orderType = 0;
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            orderType = cartPromotionItem.getType();
            String skuKey = new StringBuffer(RedisKey.ROUND_SKU_STOCK_KEY).append(cartPromotionItem.getProductId()).append("_").append(cartPromotionItem.getProductSkuId()).toString();
            Object o = this.redisService.get(skuKey);
            MarketSmsRoundProduct marketSmsRoundProduct=null;
            if(o!=null){
                marketSmsRoundProduct= (MarketSmsRoundProduct)o ;
            }
            if(marketSmsRoundProduct!=null){
                orderType  = marketSmsRoundProduct.getType();
            }else{
                orderType = cartPromotionItem.getType();
            }
            //生成下单商品信息
            OmsOrderItem orderItem = new OmsOrderItem();
            orderItem.setProductId(cartPromotionItem.getProductId());
            orderItem.setProductPic(cartPromotionItem.getProductPic());
            orderItem.setProductName(cartPromotionItem.getProductName());
            orderItem.setProductAttr(cartPromotionItem.getProductAttr());
            orderItem.setProductBrand(cartPromotionItem.getProductBrand());
            orderItem.setProductSn(cartPromotionItem.getProductSn());
            orderItem.setProductPrice(cartPromotionItem.getPrice());
            orderItem.setProductQuantity(cartPromotionItem.getQuantity());
            orderItem.setProductSkuId(cartPromotionItem.getProductSkuId());
            orderItem.setProductSkuCode(cartPromotionItem.getProductSkuCode());
            orderItem.setProductCategoryId(cartPromotionItem.getProductCategoryId());
            orderItem.setPromotionAmount(cartPromotionItem.getReduceAmount());
            orderItem.setPromotionName(cartPromotionItem.getPromotionMessage());
            //商品的积分
            Integer integration = cartPromotionItem.getIntegration();
            Integer quantity = cartPromotionItem.getQuantity();
            int totalIntegration = integration * quantity;
            orderItem.setGiftIntegration(totalIntegration);
            orderItem.setGiftGrowth(cartPromotionItem.getGrowth());
            orderItem.setCommissionAmount(cartPromotionItem.getCommissionAmount());
            orderItem.setStatus(OmsOrderItem.STATUS.WAIT_PAY.value());
            orderItem.setProductType(cartPromotionItem.getType());
            orderItem.setProductSubTitle(cartPromotionItem.getProductSubTitle());
            orderItem.setOrderId(store.getId());//门店id
            orderItem.setMemberId(currentMember.getId());//买家id
            orderItemList.add(orderItem);

        }
        //判断购物车中商品是否都有库存
        if (!hasStock(cartPromotionItemList)) {
            Asserts.fail("库存不足，无法下单");
        }
        //判断使用使用了优惠券
        if (orderParam.getCouponId() == null) {
            //不用优惠券
            for (OmsOrderItem orderItem : orderItemList) {
                orderItem.setCouponAmount(new BigDecimal(0));
            }
        } else {
            //使用优惠券
            SmsCouponHistoryDetail couponHistoryDetail = getUseCoupon(cartPromotionItemList, orderParam, orderParam.getCouponId());
            if (couponHistoryDetail == null) {
                Asserts.fail("该优惠券不可用");
            }
            //对下单商品的优惠券进行处理
            handleCouponAmount(orderItemList, couponHistoryDetail);
        }
        //判断是否使用积分
        if (orderParam.getUseIntegration() == null || orderParam.getUseIntegration().equals(0)) {
            //不使用积分
            for (OmsOrderItem orderItem : orderItemList) {
                orderItem.setIntegrationAmount(new BigDecimal(0));
            }
        } else {
            //使用积分
            BigDecimal totalAmount = calcTotalAmount(orderItemList);
            BigDecimal integrationAmount = getUseIntegrationAmount(orderParam.getUseIntegration(), totalAmount, currentMember, orderParam.getCouponId() != null);
            if (integrationAmount.compareTo(new BigDecimal(0)) == 0) {
                Asserts.fail("积分不可用");
            } else {
                //可用情况下分摊到可用商品中
                for (OmsOrderItem orderItem : orderItemList) {
                    BigDecimal perAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(integrationAmount);
                    orderItem.setIntegrationAmount(perAmount);
                }
            }
        }
        //计算order_item的实付金额
        handleRealAmount(orderItemList);
        //进行库存锁定
        lockStock(cartPromotionItemList, currentMember);
        //根据商品合计、运费、活动优惠、优惠券、积分计算应付金额
        OmsOrder order = new OmsOrder();
        order.setDiscountAmount(new BigDecimal(0));
        order.setTotalAmount(calcTotalAmount(orderItemList));
        order.setFreightAmount(new BigDecimal(0));
        order.setPromotionAmount(calcPromotionAmount(orderItemList));
        order.setPromotionInfo(getOrderPromotionInfo(orderItemList));
        order.setUserStoreId(store.getId());
        order.setUserId(store.getUserId());
        order.setNote(orderParam.getNote());
        order.setLat(orderParam.getLat());
        order.setLon(orderParam.getLon());
        if (orderParam.getCouponId() == null) {
            order.setCouponAmount(new BigDecimal(0));
        } else {
            order.setCouponId(orderParam.getCouponId());
            order.setCouponAmount(calcCouponAmount(orderItemList));
        }
        if (orderParam.getUseIntegration() == null) {
            order.setIntegration(0);
            order.setIntegrationAmount(new BigDecimal(0));
        } else {
            order.setIntegration(orderParam.getUseIntegration());
            order.setIntegrationAmount(calcIntegrationAmount(orderItemList));
        }
        order.setPayAmount(calcPayAmount(order));
        //转化为订单信息并插入数据库
        order.setMemberId(currentMember.getId());
        order.setCreateTime(new Date());
        order.setMemberUsername(currentMember.getUsername());
        //支付方式：0->未支付；1->支付宝；2->微信
        Integer payType = orderParam.getPayType();
        if(payType==null){
            payType=2;
        }
        order.setPayType(payType);
        //订单来源：0->PC订单；1->app订单
        order.setSourceType(1);
        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setStatus(0);
        //订单类型：0->普通商品；1->组合商品
        order.setOrderType(orderType);
        //收货人信息：姓名、电话、邮编、地址
        UmsMemberReceiveAddress address = memberReceiveAddressService.getItem(orderParam.getMemberReceiveAddressId());
        if (address != null) {
            order.setReceiverName(address.getName());
            order.setReceiverPhone(address.getPhoneNumber());
            order.setReceiverPostCode(address.getPostCode());
            order.setReceiverProvince(address.getProvince());
            order.setReceiverCity(address.getCity());
            order.setReceiverRegion(address.getRegion());
            order.setReceiverDetailAddress(address.getDetailAddress());
        }
        //0->未确认；1->已确认
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
        //计算赠送积分
        order.setIntegration(calcGifIntegration(orderItemList));
        //计算赠送成长值
        order.setGrowth(calcGiftGrowth(orderItemList));
        //生成订单号
        order.setOrderSn(generateOrderSn(order));
        order.setAgentId(currentMember.getAgentId());
        //设置自动收货天数
        List<OmsOrderSetting> orderSettings = this.orderSettingMapper.selectByExample(new OmsOrderSettingExample());
        if (CollUtil.isNotEmpty(orderSettings)) {
            order.setAutoConfirmDay(orderSettings.get(0).getConfirmOvertime());
        }
        Integer replaceOrder = orderParam.getReplaceOrder();
        if (replaceOrder != null && replaceOrder.equals(1)) {//是代下单
            order.setReplaceOrder(1);
            order.setReplaceAgentId(currentMember.getId());
            order.setReplaceUserId(orderParam.getReplaceUserId());
            order.setAgentId(currentMember.getId());
        } else {
            order.setReplaceOrder(replaceOrder);
        }
        //插入order表和order_item表
        this.orderMapper.insertSelective(order);
        for (OmsOrderItem orderItem : orderItemList) {
            //在这里设置佣金，因为这里的优惠是全的。
            //佣金比例* 购买数量*（价格-会员优惠价-优惠券优惠）
            PmsProductDto pmsProductDto = this.orderItemDao.getPmsProductDtoBySkuId(orderItem.getProductSkuId());
            BigDecimal multiply = new BigDecimal(orderItem.getProductQuantity()).multiply(pmsProductDto.getCommission())
                    .multiply(orderItem.getProductPrice().subtract(orderItem.getPromotionAmount()).subtract(orderItem.getCouponAmount()))
                    .divide(BigDecimal.TEN.multiply(BigDecimal.TEN), 2);
            orderItem.setCommissionAmount(multiply);
            orderItem.setOrderId(order.getId());
            orderItem.setOrderSn(order.getOrderSn());
        }
        int ii = this.orderItemDao.insertList(orderItemList);
        //如使用优惠券更新优惠券使用状态
        if (orderParam.getCouponId() != null) {
            if(replaceOrder != null && replaceOrder.equals(1)){
                updateCouponStatus(orderParam.getCouponId(), orderParam.getReplaceUserId(), 1,order.getOrderSn());
            }else{
                updateCouponStatus(orderParam.getCouponId(), currentMember.getId(), 1,order.getOrderSn());
            }

        }
        //如使用积分需要扣除积分
        if (orderParam.getUseIntegration() != null) {
            order.setUseIntegration(orderParam.getUseIntegration());
            this.memberService.updateIntegration(currentMember.getId(), currentMember.getIntegration() - orderParam.getUseIntegration());
        }
        if (type.equals(1)) {//购物车下单
            //删除购物车中的下单商品
            deleteCartItemList(cartPromotionItemList, currentMember);
        }
        if(order.getOrderType()!=2&&order.getOrderType()!=3&&order.getOrderType()!=5){
            //发送延迟消息取消订单
            sendDelayMessageCancelOrder(order.getId());
        }
//        Integer count = this.orderItemDao.upDateSale(orderItemList);
        return order.getId();
    }

    @Override
    public Integer paySuccess(String orderSn, Integer payType) {
        int count = 0;
        //修改订单支付状态
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andOrderSnEqualTo(orderSn);
        List<OmsOrder> omsOrders = orderMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(omsOrders)) {//支付成功
            OmsOrder o = omsOrders.get(0);
            int status = 1;
            List<Long> groupBuyOrderIdsByOrderId = new ArrayList<>();
            if (o.getOrderType() == 3) {
                groupBuyOrderIdsByOrderId = this.activity.getGroupBuyOrderIdsByOrderId(o.getId());
                Long aLong = groupBuyOrderIdsByOrderId.get(0);
                if (aLong.equals(-1L)) {
                    status = 8;
                } else if(aLong.equals(0L)){
                    status = 1;
                }
                groupBuyOrderIdsByOrderId.remove(0);
            }else{
                groupBuyOrderIdsByOrderId.add(o.getId());
            }
            if(!CollectionUtils.isEmpty(groupBuyOrderIdsByOrderId)){
                for (Long id:groupBuyOrderIdsByOrderId) {
                    OmsOrder order = this.orderMapper.selectByPrimaryKey(id);
                    order.setStatus(status);
                    if(order.getPaymentTime()==null){
                        order.setPaymentTime(new Date());
                    }
                    order.setPayType(payType);
                    if (order.getReplaceOrder().equals(1)) {//待别人下单
                        order.setMemberId(order.getReplaceUserId());
                        order.setMemberUsername(this.memberService.getById(order.getReplaceUserId()).getUsername());
                    }
                    orderMapper.updateByPrimaryKeySelective(order);
                    OmsOrderDetail orderDetail = portalOrderDao.getDetail(order.getId());
                    List<OmsOrderItem> collect = orderDetail.getOrderItemList().stream().filter(omsOrderItem -> (OmsOrderItem.STATUS.WAIT_PAY.value() == omsOrderItem.getStatus()||OmsOrderItem.STATUS.WAIT_GROUP.value() == omsOrderItem.getStatus())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)) {
                        if (order.getOrderType() == 3) {
                            if (status == 8) {
                                count = orderItemDao.updateOrderItemStatus(collect, OmsOrderItem.STATUS.WAIT_GROUP.value());
                            } else {
                                count = orderItemDao.updateOrderItemStatus(collect, OmsOrderItem.STATUS.WAIT_SEND.value());
                            }
                        } else {
                            count = orderItemDao.updateOrderItemStatus(collect, OmsOrderItem.STATUS.WAIT_SEND.value());
                        }
                    }
                    //买商品加积分
                    //查询子订单
                    OmsOrderItemExample itemExample = new OmsOrderItemExample();
                    itemExample.createCriteria().andOrderIdEqualTo(order.getId());
                    List<OmsOrderItem> omsOrderItems = orderItemMapper.selectByExample(itemExample);
                    //把子订单可获得的积分加一起
                    int sum = omsOrderItems.stream().mapToInt(OmsOrderItem::getGiftIntegration).sum();
                    if(sum != 0){
                        UmsMember member = memberMapper.selectByPrimaryKey(order.getMemberId());
                        int integration = member.getIntegration() != null ? member.getIntegration() : 0;
                        member.setIntegration(sum + integration);
                        this.memberMapper.updateByPrimaryKeySelective(member);
                        //重置用户缓存
                        this.memberService.handleRedis(member);
                        UmsIntegrationChangeHistory umsIntegrationChangeHistory = memberService.creatIntegrationChange(member, sum, "购买商品", 0, 0);
                        this.integrationMapper.insertSelective(umsIntegrationChangeHistory);
                    }
                    //增加销量
                    this.orderItemDao.upDateSale(omsOrderItems);
                }
            }
        }else{//开通会员
            String[] split = orderSn.split("-");
            Long memberLeverId = Long.valueOf(split[1]);
            Long memberId = Long.valueOf(split[2]);
            count = this.memberService.updateMemberLevel(this.memberService.getById(memberId), memberLeverId);
        }
        return count;
    }

    @Override
    public Integer cancelTimeOutOrder() {
        Integer count = 0;
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        //查询超时、未支付的订单及订单详情
        List<OmsOrderDetail> timeOutOrders = portalOrderDao.getTimeOutOrders(orderSetting.getNormalOrderOvertime());
        if (CollectionUtils.isEmpty(timeOutOrders)) {
            return count;
        }
        //修改订单状态为交易取消
        List<Long> ids = new ArrayList<>();
        for (OmsOrderDetail timeOutOrder : timeOutOrders) {
            ids.add(timeOutOrder.getId());
        }
        portalOrderDao.updateOrderStatus(ids, 4);
        for (OmsOrderDetail timeOutOrder : timeOutOrders) {
            if (!CollectionUtils.isEmpty(timeOutOrder.getOrderItemList())) {
                //处理营销活动中的库存
                //订单类型：0->普通商品；1->组合商品；2->秒杀商品；3->团购商品；4->换货商品；
                List<OmsOrderItem> orderItemList = timeOutOrder.getOrderItemList();
                this.cancelActivityStock(timeOutOrder.getOrderType(),orderItemList);
                //解除订单商品库存锁定
                releaseSkuStockLock(timeOutOrder.getOrderItemList());
                orderItemDao.updateOrderItemStatus(timeOutOrder.getOrderItemList(), OmsOrderItem.STATUS.CLOSE.value());
                //修改优惠券使用状态
                updateCouponStatus(timeOutOrder.getCouponId(), timeOutOrder.getMemberId(), 0,null);
            }
        }
        return timeOutOrders.size();
    }


    @Override
    public void cancelOrder(Long orderId, String note,Boolean cancelWaitGroupBuy) {
        //查询未付款的取消订单
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andIdEqualTo(orderId).andDeleteStatusEqualTo(0);
        List<OmsOrder> cancelOrderList = orderMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(cancelOrderList)) {
            return;
        }
        OmsOrder cancelOrder = null;
        if(cancelOrderList.get(0)!=null&&(cancelOrderList.get(0).getStatus()==0||(cancelOrderList.get(0).getStatus()==8&&cancelWaitGroupBuy))){
            cancelOrder = cancelOrderList.get(0);
        }
        if (cancelOrder != null) {
            boolean needReturnMoney = false;
            if(cancelOrder.getStatus()==8){
                needReturnMoney = true;
            }
            //修改订单状态为取消
            cancelOrder.setStatus(4);
            //设置取消订单原因
            cancelOrder.setNote(note);
            orderMapper.updateByPrimaryKeySelective(cancelOrder);
            OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
            orderItemExample.createCriteria().andOrderIdEqualTo(orderId);
            List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
            this.cancelActivityStock(cancelOrder.getOrderType(),orderItemList);
            //解除订单商品库存锁定
            if (!CollectionUtils.isEmpty(orderItemList)) {
                releaseSkuStockLock(orderItemList);
                orderItemDao.updateOrderItemStatus(orderItemList, OmsOrderItem.STATUS.CLOSE.value());
            }
            //修改优惠券使用状态
            updateCouponStatus(cancelOrder.getCouponId(), cancelOrder.getMemberId(), 0,null);
            if(cancelOrder.getOrderType().equals(3)){
                MarketSmsGroupBuyOrderExample groupBuyOrderExample = new MarketSmsGroupBuyOrderExample();
                groupBuyOrderExample.createCriteria().andOrderIdEqualTo(orderId);
                List<MarketSmsGroupBuyOrder> marketSmsGroupBuyOrders = this.smsGroupBuyOrderMapper.selectByExample(groupBuyOrderExample);
                if(!CollectionUtils.isEmpty(marketSmsGroupBuyOrders)){
                    //处理团购订单
                    MarketSmsGroupBuyOrder marketSmsGroupBuyOrder = marketSmsGroupBuyOrders.get(0);
                    marketSmsGroupBuyOrder.setStatus(MarketSmsGroupBuyOrder.STATUS.CANCEL.STATUS);
                    this.smsGroupBuyOrderMapper.updateByPrimaryKeySelective(marketSmsGroupBuyOrder);
                    MarketSmsGroupBuy groupBuy = this.smsGroupBuyMapper.selectByPrimaryKey(marketSmsGroupBuyOrder.getGroupBuyId());
                    MarketSmsGroupBuyOrderExample orderExample = new MarketSmsGroupBuyOrderExample();
                    orderExample.createCriteria().andGroupBuyIdEqualTo(groupBuy.getId());
                    List<MarketSmsGroupBuyOrder> orders = this.smsGroupBuyOrderMapper.selectByExample(orderExample);
                    if(!CollectionUtils.isEmpty(orders)){
                        List<Long> collect = orders.stream().map(MarketSmsGroupBuyOrder::getOrderId).collect(Collectors.toList());
                        if(!CollectionUtils.isEmpty(collect)){
                            List<Map<String, String>> picList = this.activity.getPicList(collect);
                            if(picList.size()==0){
                                //订单已经全部取消
                                groupBuy.setStatus(MarketSmsGroupBuy.STATUS.CANCEL.STATUS);
                                this.smsGroupBuyMapper.updateByPrimaryKeySelective(groupBuy);
                            }
                        }
                    }
                }
            }
            if(needReturnMoney){
                //调用微信退款接口
                WxRefundDTO wxRefundDTO = new WxRefundDTO(cancelOrder.getOrderSn(),null);
                //获取订单总金额，设置保留两位小数，并且四舍五入
                BigDecimal omsOrderMoney =cancelOrder.getPayAmount().multiply(BigDecimal.TEN).multiply(BigDecimal.TEN);
                wxRefundDTO.setTotal_fee(String.valueOf(omsOrderMoney.intValue()));
                //获取退款金额，并设置
                wxRefundDTO.setRefund_fee(String.valueOf(omsOrderMoney.intValue()));
                this.refundService.refund(wxRefundDTO);
                System.out.println("退款成功--------------");
            }
        }
    }
    private void cancelActivityStock(Integer type, List<OmsOrderItem> orderItemList) {
        orderItemList.stream().forEach(e -> {
            if (type.equals(2) || type.equals(3)) {
                String stockKey = new StringBuffer(RedisKey.ROUND_SKU_STOCK_KEY).append(e.getProductId()).append("_").append(e.getProductSkuId()).toString();
                Object o = this.redisService.get(stockKey);
                if(o!=null){
                    MarketSmsRoundProduct skuStockProduct = (MarketSmsRoundProduct)o ;
                    String productKey = new StringBuffer(RedisKey.ROUND_PRODUCT_KEY).append(skuStockProduct.getId()).toString();
                    Object o1 = this.redisService.get(productKey);
                    if(o1!=null){
                        MarketSmsRoundProduct marketSmsRoundProduct = (MarketSmsRoundProduct) o1;
                        Object o2 = this.redisService.get(RedisKey.ROUND_STARTING_KEY + skuStockProduct.getRoundId());
                        if(o2!=null){
                            MarketSmsRound ro = (MarketSmsRound) o2;
                            marketSmsRoundProduct.setResidueNum(marketSmsRoundProduct.getResidueNum() + e.getProductQuantity());
                            this.redisService.setMilliSeconds(productKey, marketSmsRoundProduct, DateUtil.getReduce(ro.getEndTime()));
                            this.redisService.setMilliSeconds(stockKey, marketSmsRoundProduct, DateUtil.getReduce(ro.getEndTime()));
                        }
                    }
                }
            }
        });
    }
    @Override
    public void sendDelayMessageCancelOrder(Long orderId) {
        long delayTimes = 0L;
        //获取订单超时时间
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        OmsOrder omsOrder = this.orderMapper.selectByPrimaryKey(orderId);
        switch (omsOrder.getOrderType()){
            case 0: //普通商品
            case 1: //组合商品
            case 4: //换货商品
                delayTimes= orderSetting.getNormalOrderOvertime() * 60 * 1000;
                break;
            case 2: //秒杀
                delayTimes= orderSetting.getFlashOrderOvertime() * 60 * 1000;
                break;
            case 3: //团购商品
                delayTimes= orderSetting.getGroupBuyOrderOvertime() * 60 * 1000;
                break;
        }
        //发送延迟消息
        messageSender.sendMessage(orderId, delayTimes, QueueEnum.QUEUE_TTL_ORDER_CANCEL);
    }

    @Override
    @Transactional
    public void confirmReceiveOrder(Long orderId) {
        OmsOrderDetail detail = this.portalOrderDao.getDetail(orderId);
        List<OmsOrderItem> collect = detail.getOrderItemList().stream().filter(omsOrderItem -> OmsOrderItem.STATUS.WAIT_RECEIVE.value() == omsOrderItem.getStatus()).collect(Collectors.toList());
        //不是待收货状态的子订单
        List<OmsOrderItem> collectElse = detail.getOrderItemList().stream().filter(omsOrderItem -> OmsOrderItem.STATUS.RETURNING_GOODS.value() == omsOrderItem.getStatus()).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collectElse)) {
            for (OmsOrderItem item : collectElse){
                OmsOrderReturnApplyExample example = new OmsOrderReturnApplyExample();
                //查看是否存在换货的子订单
                example.createCriteria().andOrderItemIdEqualTo(item.getId()).andOrderTypeEqualTo(2).andReturnStatusEqualTo(2);
                List<OmsOrderReturnApply> omsOrderReturnApplies = returnApplyMapper.selectByExample(example);
                if (!CollectionUtils.isEmpty(omsOrderReturnApplies)) {
                    collect.add(item);
                }
            }
        }
        if (!CollectionUtils.isEmpty(collect)) {
            System.out.println("确认订单");
            UmsMember member = memberService.getCurrentMember();
            OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
            if (!member.getId().equals(order.getMemberId())) {
                Asserts.fail("不能确认他人订单！");
            }
            if (order.getStatus() != 2) {
                Asserts.fail("该订单还未发货！");
            }
            order.setStatus(3);
            order.setConfirmStatus(1);
            order.setReceiveTime(new Date());
            orderMapper.updateByPrimaryKey(order);
            System.out.println("确认订单collect");
            this.orderItemDao.updateOrderItemStatus(collect, OmsOrderItem.STATUS.FINISH.value());
            if(!order.getOrderType().equals(4)){
                this.messageSender.sendMessage(orderId, 0, QueueEnum.QUEUE_DISTRIBUTION_CREAT);
            }
        }else{
            Asserts.fail("该订单下没有待收货的商品，不能确认收货");
        }
    }

    @Override
    public Map<String, Object> list(Integer status, String productName, Integer pageNum, Integer pageSize, Integer type, Integer agentSendType, Long memberId) {
        Map<String, Object> result = new HashMap<>();

        UmsMember member = memberService.getCurrentMember();
        OmsOrderExample orderExample = new OmsOrderExample();
        OmsOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0);
        if (type.equals(0)) {
            //判断是不是经纪人
            if (member.getType().equals(1)) {
                //经纪人
                criteria.andReplaceOrderEqualTo(0);
            }
            criteria.andMemberIdEqualTo(member.getId());
        } else if (type.equals(1)) {
            criteria.andReplaceAgentIdEqualTo(member.getId())
                    .andReplaceUserIdEqualTo(memberId);
        } else if (type.equals(2)) {
            criteria.andAgentIdEqualTo(member.getId());
            if (agentSendType != 3) {
                criteria.andAgentSendTypeEqualTo(agentSendType);
            }else{
                criteria.andAgentSendTypeIn(Arrays.asList(new Integer[]{1,2}));
            }
        }
//        if(status!=null){
//            if (status.equals(4)){
//                Integer hStatus = 5;
//                Integer kStatus = 6;
//                List<Integer> returnStatus = new ArrayList<>();
//                returnStatus.add(hStatus);
//                returnStatus.add(kStatus);
//                criteria.andStatusIn(returnStatus);
//            }else {
//                criteria.andStatusEqualTo(status);
//            }
//        }
        if (status.equals(-1)) {
            status = null;
        } else {
            criteria.andStatusEqualTo(status);
        }
        //商品名的查询，先查子订单，根据子订单查商品
        List<Long> orders = new ArrayList<>();
        boolean flag = false;
        if (productName != null && !"".equals(productName)) {
            OmsOrderItemExample itemExample = new OmsOrderItemExample();
            itemExample.createCriteria().andProductNameLike("%" + productName + "%");
            List<OmsOrderItem> omsOrderItems = orderItemMapper.selectByExample(itemExample);
            if (!CollectionUtils.isEmpty(omsOrderItems)) {
                orders = omsOrderItems.stream().map(OmsOrderItem::getOrderId).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(orders)) {
                criteria.andIdIn(orders);
                flag = true;
            }
        }else{
            flag = true;
        }

        //全部订单不返售后单
        criteria.andStatusNotEqualTo(5).andStatusNotEqualTo(6);
        orderExample.setOrderByClause("create_time desc");
        PageHelper.startPage(pageNum, pageSize);
        List<OmsOrder> orderList = orderMapper.selectByExample(orderExample);
        if(!flag){
            orderList = new ArrayList<>();
        }
        CommonPage<OmsOrder> orderPage = CommonPage.restPage(orderList);
        //设置分页信息
        CommonPage<OmsOrderDetail> resultPage = new CommonPage<>();
        resultPage.setPageNum(orderPage.getPageNum());
        resultPage.setPageSize(orderPage.getPageSize());
        resultPage.setTotal(orderPage.getTotal());
        resultPage.setTotalPage(orderPage.getTotalPage());
        if (CollUtil.isEmpty(orderList)) {
            result.put("stockMap", new ArrayList<>());
            result.put("pageInfo", resultPage);
            return result;
        }
        //设置数据信息
        List<Long> orderIds = orderList.stream().map(OmsOrder::getId).collect(Collectors.toList());
        OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
        orderItemExample.createCriteria().andOrderIdIn(orderIds);
        List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
        List<OmsOrderDetail> orderDetailList = new ArrayList<>();
        for (OmsOrder omsOrder : orderList) {
            OmsOrderDetail orderDetail = new OmsOrderDetail();
            BeanUtil.copyProperties(omsOrder, orderDetail);
            List<OmsOrderItem> relatedItemList = orderItemList.stream().filter(item -> item.getOrderId().equals(orderDetail.getId())).collect(Collectors.toList());
            int sum = 0;
            if (!CollectionUtils.isEmpty(relatedItemList)) {
                for (OmsOrderItem o : relatedItemList) {
                    Integer productQuantity = o.getProductQuantity();
                    sum += productQuantity;
                }
            }
            orderDetail.setTotalQuantity(sum);
            orderDetail.setOrderItemList(relatedItemList);
            OmsOrderReturnApplyExample example = new OmsOrderReturnApplyExample();
            example.createCriteria().andOrderIdEqualTo(omsOrder.getId()).andOrderItemStatusEqualTo(omsOrder.getStatus());
            List<OmsOrderReturnApply> orderReturnApplyList = returnApplyMapper.selectByExample(example);
            OmsOrderReturnApply returnApply = orderReturnApplyList.stream().filter(o -> (o.getOrderId().equals(omsOrder.getId()))).findAny().orElse(null);
            if (returnApply == null) {
                orderDetail.setReturnType(null);
                orderDetail.setReturnStatus(null);
                orderDetail.setReturnOrderSn(null);
                orderDetail.setReturnAmount(null);
                orderDetail.setReturnDescription(null);
                orderDetail.setReturnCreateTime(null);
                orderDetail.setReturnReason(null);
                orderDetail.setReturnHandleTime(null);
            } else {
                orderDetail.setReturnType(returnApply.getOrderType());
                orderDetail.setReturnStatus(returnApply.getReturnStatus());
                orderDetail.setReturnOrderSn(returnApply.getOrderSn());
                orderDetail.setReturnAmount(returnApply.getReturnAmount());
                orderDetail.setReturnDescription(returnApply.getDescription());
                orderDetail.setReturnCreateTime(returnApply.getCreateTime());
                orderDetail.setReturnReason(returnApply.getReason());
                orderDetail.setReturnHandleTime(returnApply.getHandleTime());
            }
            if (relatedItemList.size() > 0) {
                orderDetail.setProductType(relatedItemList.get(0).getProductType());
            }
            if (orderItemList.size() > 0) {
                orderDetail.setProductType(orderItemList.get(0).getProductType());
            }
            orderDetailList.add(orderDetail);
        }
//        if (type.equals(2)) {
//            OmsAgentSendExample example = new OmsAgentSendExample();
//            example.createCriteria().andOrderIdIn(orderIds);
//            List<OmsAgentSend> omsAgentSends = this.omsAgentSendMapper.selectByExample(example);
//            Map<Long, List<OmsAgentSend>> agentSendMap = omsAgentSends.stream().collect(Collectors.groupingBy(e -> e.getSkuId()));
//            result.put("stockMap", agentSendMap);
//        }
        resultPage.setList(orderDetailList);
        result.put("pageInfo", resultPage);
        return result;
    }

    @Override
    public OmsOrderDetail detail(Long orderId) {
        int productType = 0;
        OmsOrder omsOrder = orderMapper.selectByPrimaryKey(orderId);
        OmsOrderItemExample example = new OmsOrderItemExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(example);
        //查询组合商品信息返回
        List<OrderItemDetail> orderItemDetails = new ArrayList<>();
        OmsOrderReturnApplyExample ooraExample = new OmsOrderReturnApplyExample();
        ooraExample.createCriteria().andOrderIdEqualTo(omsOrder.getId());
        ooraExample.setOrderByClause("id");
        List<OmsOrderReturnApply> orderReturnApplyList = returnApplyMapper.selectByExample(ooraExample);
        Map<Long, List<OmsOrderReturnApply>> returnMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orderReturnApplyList)) {
            returnMap = orderReturnApplyList.stream().collect(Collectors.groupingBy(OmsOrderReturnApply::getOrderItemId));
        }
        Map<String, List<OmsAgentSend>> agentSendMap = new HashMap<>();
        if(!omsOrder.getAgentSendType().equals(0)){
            OmsAgentSendExample omsAgentSendExample = new OmsAgentSendExample();
            omsAgentSendExample.createCriteria().andOrderIdEqualTo(orderId);
            List<OmsAgentSend> omsAgentSends = this.omsAgentSendMapper.selectByExample(omsAgentSendExample);
            agentSendMap= omsAgentSends.stream().collect(Collectors.groupingBy(e -> (e.getOrderItemId()+"_"+e.getSkuId())));
        }
        MarketSmsRound ro = null;
        for (OmsOrderItem p : orderItemList) {
            OrderItemDetail orderItemDetail = new OrderItemDetail();
            BeanUtils.copyProperties(p, orderItemDetail);
            List<ProductDeitail> productDeitailList = null;
            List<ProductDeitail> productDeitailListRes = new ArrayList<>();
            if (p.getProductType() != null && p.getProductType().equals(1)) {
                PmsSkuStockExample pmsSkuStockExample = new PmsSkuStockExample();
                pmsSkuStockExample.createCriteria().andProductIdEqualTo(p.getProductId());
                Long parentId = pmsSkuStockMapper.selectByExample(pmsSkuStockExample).get(0).getId();
                productDeitailList = pmsCombinedProductDao.selectOrderProductDetail(parentId);
                productType = 1;
                if(!CollectionUtils.isEmpty(productDeitailList)){
                    for (ProductDeitail e:productDeitailList) {
                        String key = p.getId()+"_"+e.getSkuId();
                        e.setOmsAgentSends(agentSendMap.get(key));
                        productDeitailListRes.add(e);
                    }
                }else{
                    productDeitailListRes = productDeitailList;
                }
            }
            orderItemDetail.setProductDeitailList(productDeitailListRes);
            List<OmsOrderReturnApply> omsOrderReturnApplies = returnMap.get(p.getId());
            if (!CollectionUtils.isEmpty(omsOrderReturnApplies)) {
                OmsOrderReturnApply omsOrderReturnApply = omsOrderReturnApplies.get(omsOrderReturnApplies.size()-1);
                orderItemDetail.setReturnStatus(omsOrderReturnApply.getReturnStatus());
                orderItemDetail.setReturnType(omsOrderReturnApply.getOrderType());
            }
            if(agentSendMap!=null&&productType==1){
                String key = p.getId()+"_"+p.getProductSkuId();
                orderItemDetail.setOmsAgentSends(agentSendMap.get(key));
            }
            String productKey = RedisKey.ROUND_SKU_STOCK_KEY+p.getProductId()+"_"+p.getProductSkuId();
            Object o = this.redisService.get(productKey);
            if(o!=null){
                //还在活动中
                MarketSmsRoundProduct roundProduct =  (MarketSmsRoundProduct)o;
                ro = (MarketSmsRound)this.redisService.get(RedisKey.ROUND_STARTING_KEY + roundProduct.getRoundId());
            }
            orderItemDetails.add(orderItemDetail);
        }
        OmsOrderDetail orderDetail = new OmsOrderDetail();
        BeanUtil.copyProperties(omsOrder, orderDetail);
        int sum = 0;
        if (!CollectionUtils.isEmpty(orderItemList)) {
            for (OmsOrderItem o : orderItemList) {
                Integer productQuantity = o.getProductQuantity();
                sum += productQuantity;
            }
        }
        orderDetail.setTotalQuantity(sum);
        //orderDetail.setOrderItemList(orderItemList);
        orderDetail.setOrderItemDetails(orderItemDetails);
        // orderDetail.setOrderItemList(orderItemList);

        //获取订单时间设置
        List<OmsOrderSetting> omsOrderSettings = settingMapper.selectByExample(new OmsOrderSettingExample());
        OmsOrderSetting omsOrderSetting = omsOrderSettings.get(0);
        int sen = omsOrderSetting.getNormalOrderOvertime() * 60 * 1000;
        Date createTime = omsOrder.getCreateTime();
        Date afterDate = new Date(createTime.getTime() + sen);
        Date now = new Date();
        OmsOrderSetting result = new OmsOrderSetting();
        Long normalOrderOvertime = 0L;
        Long groupBuyAutoCancel = 0L;
        if (omsOrder.getOrderType().equals(1) || omsOrder.getOrderType().equals(0)) {
            if (afterDate.after(now)) {
                //订单结束时间小于当前时间
                long l = afterDate.getTime() - now.getTime();
                normalOrderOvertime =  l;
            }
        }else {
            if (ro != null) {
                MarketSmsGroupBuy groupBuy = null;
                if (omsOrder.getOrderType().equals(3)) {
                    //团购
                    MarketSmsGroupBuyOrderExample example1 = new MarketSmsGroupBuyOrderExample();
                    example1.createCriteria().andOrderIdEqualTo(omsOrder.getId());
                    List<MarketSmsGroupBuyOrder> marketSmsGroupBuyOrders = this.smsGroupBuyOrderMapper.selectByExample(example1);
                    if(!CollectionUtils.isEmpty(marketSmsGroupBuyOrders)){
                        groupBuy = this.smsGroupBuyMapper.selectByPrimaryKey(marketSmsGroupBuyOrders.get(0).getGroupBuyId());
                        MarketSmsGroupBuyOrderExample groupBuyOrderExample = new MarketSmsGroupBuyOrderExample();
                        groupBuyOrderExample.createCriteria().andGroupBuyIdEqualTo(groupBuy.getId());
                        List<MarketSmsGroupBuyOrder> orders = this.smsGroupBuyOrderMapper.selectByExample(groupBuyOrderExample);
                        if(!CollectionUtils.isEmpty(orders)){
                            List<Long> orderIds = orders.stream().map(MarketSmsGroupBuyOrder::getOrderId).collect(Collectors.toList());
                            List<Map<String, String>> picList = this.activity.getPicList(orderIds);
                            orderDetail.setGroupSize(groupBuy.getGroupSize());
                            orderDetail.setOrderBodyNum(picList.size());
                            orderDetail.setPics(picList);
                        }
                        //团购失效时长
                        groupBuyAutoCancel = groupBuy.getAddTime().getTime()+omsOrderSetting.getGroupBuyOrderOvertime()*60*1000-System.currentTimeMillis();
                    }
                }
                Long aLong = this.activityService.getaLong(ro, groupBuy, orderId, omsOrderSetting, omsOrder);
                if(aLong>0L){
                    normalOrderOvertime =(aLong+omsOrder.getCreateTime().getTime()-System.currentTimeMillis());
                }
            }
        }
        //把时间设置放进去
        orderDetail.setUnPayAutoCancel(normalOrderOvertime);
        orderDetail.setGroupBuyAutoCancel(groupBuyAutoCancel);
        orderDetail.setOrderSetting(result);
        orderDetail.setProductType(productType);
        return orderDetail;
    }

    @Override
    public void deleteOrder(Long orderId) {
        UmsMember member = memberService.getCurrentMember();
        OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
        if (!member.getId().equals(order.getMemberId())) {
            Asserts.fail("不能删除他人订单！");
        }
        if (order.getStatus() == 3 || order.getStatus() == 4) {
            order.setDeleteStatus(1);
            orderMapper.updateByPrimaryKey(order);
        } else {
            Asserts.fail("只能删除已完成或已关闭的订单！");
        }
    }

    @Override
    public List<SmsCouponHistoryDetail> getCouponList(Long memberId, OrderParam orderParam) {
        UmsMember member = this.memberService.getCurrentMember();
        List<OmsCartItem> cartPromotionItemList = new ArrayList<>();
        if (memberId != null && !memberId.equals(-1L)) {
            member = this.memberService.getById(memberId);
        }
        if (!CollectionUtils.isEmpty(orderParam.getCartIds())) {//是否在购物车页面调取该数据
            List<OmsCartItem> cartItemList = this.cartItemService.getList(member.getId());
            if (CollUtil.isNotEmpty(orderParam.getCartIds())) {
                cartPromotionItemList = cartItemList.stream().filter(item -> orderParam.getCartIds().contains(item.getId())).collect(Collectors.toList());
            }
        } else {
            Long skuId = orderParam.getSkuId();
            Integer quantity = orderParam.getQuantity().intValue();
            cartPromotionItemList.add(this.getOmsCartItem(skuId, quantity, member));
        }
        List<CartPromotionItem> cartPromotionItems = this.promotionService.calcCartPromotion(member.getId(), cartPromotionItemList, member.getStoreId());
        return this.memberCouponService.listCart(cartPromotionItems, member.getId(), 1);

    }

    @Override
    public Integer agentSend(Long orderId) {
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setId(orderId);
        omsOrder.setAgentSendType(2);
        return this.orderMapper.updateByPrimaryKeySelective(omsOrder);
    }

    @Override
    public Map<String, String> wxPay(Long orderId,String ipAddress,Integer type) throws Exception {
        UmsMember currentMember = this.memberService.getCurrentMember();
        OmsOrder omsOrder = this.orderMapper.selectByPrimaryKey(orderId);
        if (omsOrder.getStatus().equals(0)) {
            OmsOrderItemExample itemExample = new OmsOrderItemExample();
            itemExample.createCriteria().andOrderIdEqualTo(orderId);
            List<OmsOrderItem> omsOrderItems = this.orderItemMapper.selectByExample(itemExample);
            String body = StringUtils.join(omsOrderItems.stream().map(OmsOrderItem::getProductName).collect(Collectors.toList()).toArray(), "|");
            if (body.length() > 30) {
                body = body.substring(0,30).trim();
            }
            try {
                WxMyConfig.TRADE_TYPE trade_type = WxMyConfig.TRADE_TYPE.JSAPI;
                if (type.equals(0)) {
                    trade_type = WxMyConfig.TRADE_TYPE.MWEB;
                }
                WxPayDTO wxPayDTO = new WxPayDTO(trade_type);
                wxPayDTO.setBody(body);
                // openIdsh
                wxPayDTO.setOpenid(currentMember.getOpenId());
                // 订单号,每次都不同
                wxPayDTO.setOut_trade_no(omsOrder.getOrderSn());
                wxPayDTO.setSpbill_create_ip(ipAddress);
                // 支付类型
                wxPayDTO.setTrade_type(trade_type.VALUE());
                String fee = omsOrder.getPayAmount().multiply(BigDecimal.TEN.multiply(BigDecimal.TEN)).setScale(0).toString();
                if (fee.equals("0")) {
                    fee = "1";
                }
                wxPayDTO.setTotal_fee(fee);
//                wxPayDTO.setTotal_fee("1");
                return this.wxPayService.wxPay(wxPayDTO);
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
     */
    private String generateOrderSn(OmsOrder order) {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = REDIS_DATABASE + ":" + REDIS_KEY_ORDER_ID + date;
        Long increment = redisService.incr(key, 1);
        sb.append(date);
        sb.append(String.format("%02d", order.getSourceType()));
        sb.append(String.format("%02d", order.getPayType()));
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }

    /**
     * 删除下单商品的购物车信息
     */
    private void deleteCartItemList(List<CartPromotionItem> cartPromotionItemList, UmsMember currentMember) {
        List<Long> ids = new ArrayList<>();
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            if (cartPromotionItem.getId() != null) {
                ids.add(cartPromotionItem.getId());
            }
        }
        if (!CollectionUtils.isEmpty(ids)) {
            String join = StringUtils.join(ids, ",");
            cartItemService.delete(currentMember.getId(), join);
        }
    }

    /**
     * 计算该订单赠送的成长值
     */
    private Integer calcGiftGrowth(List<OmsOrderItem> orderItemList) {
        Integer sum = 0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum = sum + orderItem.getGiftGrowth() * orderItem.getProductQuantity();
        }
        return sum;
    }

    /**
     * 计算该订单赠送的积分
     */
    private Integer calcGifIntegration(List<OmsOrderItem> orderItemList) {
        int sum = 0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum += orderItem.getGiftIntegration();
//                    * orderItem.getProductQuantity()
        }
        return sum;
    }

    /**
     * 将优惠券信息更改为指定状态
     *
     * @param couponId  优惠券id
     * @param memberId  会员id
     * @param useStatus 0->未使用；1->已使用
     */
    private void updateCouponStatus(Long couponId, Long memberId, Integer useStatus,String orderSn) {
        if (couponId == null){ return;}
        //查询第一张优惠券
        SmsCouponHistoryExample example = new SmsCouponHistoryExample();
        example.createCriteria().andMemberIdEqualTo(memberId)
                .andCouponIdEqualTo(couponId).andUseStatusEqualTo(useStatus == 0 ? 1 : 0);
        List<SmsCouponHistory> couponHistoryList = couponHistoryMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(couponHistoryList)) {
            SmsCouponHistory couponHistory = couponHistoryList.get(0);
            SmsCoupon smsCoupon = couponMapper.selectByPrimaryKey(couponId);
            if(useStatus.equals(1)){
                couponHistory.setUseTime(new Date());
                couponHistory.setOrderSn(orderSn);
                //使用了优惠券，把优惠券的使用数量+1
                smsCoupon.setUseCount(smsCoupon.getUseCount() + 1);
            }else{
                couponHistory.setUseTime(null);
                couponHistory.setOrderSn(null);
                //回滚了优惠券，把优惠券的使用数量-1
                smsCoupon.setUseCount(smsCoupon.getUseCount() - 1);
            }
            couponHistory.setUseStatus(useStatus);
            couponHistoryMapper.updateByPrimaryKeySelective(couponHistory);
            couponMapper.updateByPrimaryKey(smsCoupon);
        }
    }

    private void handleRealAmount(List<OmsOrderItem> orderItemList) {
        for (OmsOrderItem orderItem : orderItemList) {
            //原价-促销优惠-优惠券抵扣-积分抵扣
            BigDecimal realAmount = orderItem.getProductPrice()
                    .subtract(orderItem.getPromotionAmount())
                    .subtract(orderItem.getCouponAmount())
                    .subtract(orderItem.getIntegrationAmount());
            orderItem.setRealAmount(realAmount);
        }
    }

    /**
     * 获取订单促销信息
     */
    private String getOrderPromotionInfo(List<OmsOrderItem> orderItemList) {
        StringBuilder sb = new StringBuilder();
        for (OmsOrderItem orderItem : orderItemList) {
            sb.append(orderItem.getPromotionName());
            sb.append(";");
        }
        String result = sb.toString();
        if (result.endsWith(";")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * 计算订单应付金额
     */
    private BigDecimal calcPayAmount(OmsOrder order) {
        //总金额+运费-促销优惠-优惠券优惠-积分抵扣
        BigDecimal payAmount = order.getTotalAmount()
                .add(order.getFreightAmount())
                .subtract(order.getPromotionAmount())
                .subtract(order.getCouponAmount())
                .subtract(order.getIntegrationAmount());
        return payAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcIntegrationAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal integrationAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getIntegrationAmount() != null) {
                integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return integrationAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcCouponAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal couponAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getCouponAmount() != null) {
                couponAmount = couponAmount.add(orderItem.getCouponAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return couponAmount;
    }

    /**
     * 计算订单活动优惠
     */
    private BigDecimal calcPromotionAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal promotionAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getPromotionAmount() != null) {
                promotionAmount = promotionAmount.add(orderItem.getPromotionAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return promotionAmount;
    }

    /**
     * 获取可用积分抵扣金额
     *
     * @param useIntegration 使用的积分数量
     * @param totalAmount    订单总金额
     * @param currentMember  使用的用户
     * @param hasCoupon      是否已经使用优惠券
     */
    private BigDecimal getUseIntegrationAmount(Integer useIntegration, BigDecimal totalAmount, UmsMember currentMember, boolean hasCoupon) {
        BigDecimal zeroAmount = new BigDecimal(0);
        //判断用户是否有这么多积分
        if (useIntegration.compareTo(currentMember.getIntegration()) > 0) {
            return zeroAmount;
        }
        //根据积分使用规则判断是否可用
        //是否可与优惠券共用
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
        if (hasCoupon && integrationConsumeSetting.getCouponStatus().equals(0)) {
            //不可与优惠券共用
            return zeroAmount;
        }
        //是否达到最低使用积分门槛
        if (useIntegration.compareTo(integrationConsumeSetting.getUseUnit()) < 0) {
            return zeroAmount;
        }
        //是否超过订单抵用最高百分比
        BigDecimal integrationAmount = new BigDecimal(useIntegration).divide(new BigDecimal(integrationConsumeSetting.getUseUnit()), 2, RoundingMode.HALF_EVEN);
        BigDecimal maxPercent = new BigDecimal(integrationConsumeSetting.getMaxPercentPerOrder()).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
        if (integrationAmount.compareTo(totalAmount.multiply(maxPercent)) > 0) {
            return zeroAmount;
        }
        return integrationAmount;
    }

    /**
     * 对优惠券优惠进行处理
     *
     * @param orderItemList       order_item列表
     * @param couponHistoryDetail 可用优惠券详情
     */
    private void handleCouponAmount(List<OmsOrderItem> orderItemList, SmsCouponHistoryDetail couponHistoryDetail) {
        SmsCoupon coupon = couponHistoryDetail.getCoupon();
        if (coupon.getUseType().equals(0)) {
            //全场通用
            calcPerCouponAmount(orderItemList, coupon);
        } else if (coupon.getUseType().equals(1)) {
            //指定分类
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 0);
            calcPerCouponAmount(couponOrderItemList, coupon);
        } else if (coupon.getUseType().equals(2)) {
            //指定商品
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 1);
            calcPerCouponAmount(couponOrderItemList, coupon);
        }
    }

    /**
     * 对每个下单商品进行优惠券金额分摊的计算
     *
     * @param orderItemList 可用优惠券的下单商品商品
     */
    private void calcPerCouponAmount(List<OmsOrderItem> orderItemList, SmsCoupon coupon) {
        BigDecimal totalAmount = calcTotalAmount(orderItemList);
        for (OmsOrderItem orderItem : orderItemList) {
            //(商品价格/可用商品总价)*优惠券面额
            BigDecimal couponAmount = orderItem.getProductPrice().divide(totalAmount,4,RoundingMode.HALF_UP).multiply(coupon.getAmount()).setScale(2, RoundingMode.HALF_UP);
            orderItem.setCouponAmount(couponAmount);
        }
    }

    /**
     * 获取与优惠券有关系的下单商品
     *
     * @param couponHistoryDetail 优惠券详情
     * @param orderItemList       下单商品
     * @param type                使用关系类型：0->相关分类；1->指定商品
     */
    private List<OmsOrderItem> getCouponOrderItemByRelation(SmsCouponHistoryDetail couponHistoryDetail, List<OmsOrderItem> orderItemList, int type) {
        List<OmsOrderItem> result = new ArrayList<>();
        if (type == 0) {
            List<Long> categoryIdList = new ArrayList<>();
            for (SmsCouponProductCategoryRelation productCategoryRelation : couponHistoryDetail.getCategoryRelationList()) {
                categoryIdList.add(productCategoryRelation.getProductCategoryId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (categoryIdList.contains(orderItem.getProductCategoryId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        } else if (type == 1) {
            List<Long> productIdList = new ArrayList<>();
            for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
                productIdList.add(productRelation.getProductId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (productIdList.contains(orderItem.getProductId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        }
        return result;
    }

    /**
     * 获取该用户可以使用的优惠券
     *
     * @param cartPromotionItemList 购物车优惠列表
     * @param couponId              使用优惠券id
     */
    private SmsCouponHistoryDetail getUseCoupon(List<CartPromotionItem> cartPromotionItemList, OrderParam orderParam, Long couponId) {
        Long memberId = orderParam.getReplaceOrder() == 0 ? this.memberService.getCurrentMember().getId() : orderParam.getReplaceUserId();
        List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, memberId, 1);
        for (SmsCouponHistoryDetail couponHistoryDetail : couponHistoryDetailList) {
            if (couponHistoryDetail.getCoupon().getId().equals(couponId)) {
                return couponHistoryDetail;
            }
        }
        return null;
    }

    /**
     * 计算总金额
     */
    private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal totalAmount = new BigDecimal("0");
        for (OmsOrderItem item : orderItemList) {
            totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
        }
        return totalAmount;
    }

    /**
     * 此方法没有对库存剩余数量进行判断，调用该方法的上文需要对库存进行判断 2020年9月8日 zhouboyu
     * 锁定下单商品的所有库存
     */
    private void lockStock(List<CartPromotionItem> cartPromotionItemList, UmsMember umsMember) {
        Map<Integer, List<CartPromotionItem>> map = cartPromotionItemList.stream().collect(Collectors.groupingBy(CartPromotionItem::getType));
        for (Map.Entry<Integer, List<CartPromotionItem>> entry : map.entrySet()) {
            Integer key = entry.getKey();
            List<CartPromotionItem> cpiList = entry.getValue();
            if (key.equals(1)) {//组合商品
                List<Long> parentIds = cpiList.stream().map(CartPromotionItem::getProductSkuId).collect(Collectors.toList());
                PmsCombinedProductExample example = new PmsCombinedProductExample();
                example.createCriteria().andParentIdIn(parentIds);
                List<PmsCombinedProduct> pmsCombinedProducts = this.pmsCombinedProductMapper.selectByExample(example);
                Map<Long, List<PmsCombinedProduct>> parentMap = pmsCombinedProducts.stream().collect(Collectors.groupingBy(PmsCombinedProduct::getParentId));
                for (CartPromotionItem cartPromotionItem : cpiList) {
                    List<PmsCombinedProduct> combinedProducts = parentMap.get(cartPromotionItem.getProductSkuId());
                    for (PmsCombinedProduct product : combinedProducts) {
                        Integer quantity = cartPromotionItem.getQuantity() * product.getNum();
                        Long productSkuId = product.getSkuStockId();
                        lockStock(quantity, productSkuId);
                    }
                }
            } else {//普通商品
                for (CartPromotionItem cartPromotionItem : cpiList) {
                    Integer quantity = cartPromotionItem.getQuantity();
                    Long productSkuId = cartPromotionItem.getProductSkuId();
                    lockStock(quantity, productSkuId);
                }
            }
        }
    }

    /**
     * 锁定库存  加storeid
     *
     * @param quantity 买入数量
     * @param skuId    规格编码
     */
    public void lockStock(Integer quantity, Long skuId) {
        PmsSkuStock skuStock = this.skuStockMapper.selectByPrimaryKey(skuId);
        skuStock.setLockStock(skuStock.getLockStock() + quantity);
        skuStockMapper.updateByPrimaryKeySelective(skuStock);
    }

    /**
     * 判断下单商品是否都有库存
     */
    private boolean hasStock(List<CartPromotionItem> cartPromotionItemList) {
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            if (cartPromotionItem.getRealStock() == null || cartPromotionItem.getRealStock() <= 0) {
                return false;
            } else if (cartPromotionItem.getRealStock() - cartPromotionItem.getQuantity() < 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 计算购物车中商品的价格
     */
    private ConfirmOrderResult.CalcAmount calcCartAmount(List<CartPromotionItem> cartPromotionItemList) {
        ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
        calcAmount.setFreightAmount(new BigDecimal(0));
        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal promotionAmount = new BigDecimal("0");
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            promotionAmount = promotionAmount.add(cartPromotionItem.getReduceAmount().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
        }
        calcAmount.setTotalAmount(totalAmount);
        calcAmount.setPromotionAmount(promotionAmount);
        calcAmount.setPayAmount(totalAmount.subtract(promotionAmount));
        return calcAmount;
    }

    /**
     * 获取经纪人库存列表
     *
     * @param agentId  经纪人id
     * @param pageNum
     * @param pageSize
     * @return
     * @author 孙晓亮
     * @date 2020年9月21日
     */
    @Override
    public List<AgentSkuListResult> getAgentSkuList(Long agentId, Long productCategoryId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<AgentSkuListResult> agentSkuListResults = pmsStockDao.getAgentSkuList(agentId, productCategoryId);
        return agentSkuListResults;
    }

    @Override
    public OrderItemDetail getProductFromOrderItem(Long id) {
        OmsOrderItem omsOrderItem = orderItemMapper.selectByPrimaryKey(id);
        OrderItemDetail orderItemDetail = new OrderItemDetail();
        BeanUtils.copyProperties(omsOrderItem, orderItemDetail);
        //获取组合商品
        List<ProductDeitail> productDeitailList = null;
        if (omsOrderItem.getProductType() != null && omsOrderItem.getProductType().equals(1)) {
            productDeitailList = pmsCombinedProductDao.selectOrderProductDetail(omsOrderItem.getProductSkuId());
        }
        orderItemDetail.setProductDeitailList(productDeitailList);
        BigDecimal productQuantity = new BigDecimal(omsOrderItem.getProductQuantity().toString());
        BigDecimal realAmount = omsOrderItem.getRealAmount();
        BigDecimal multiply = realAmount.multiply(productQuantity);
        orderItemDetail.setReturnAmount(multiply);
        //看商品是组合商品还是普通商品
        PmsProduct product = productMapper.selectByPrimaryKey(omsOrderItem.getProductId());
        orderItemDetail.setPType(product.getType());
        return orderItemDetail;
    }

    /**
     * 解除订单商品库存锁定
     * 区分普通商品和组合商品
     * @param orderItemList
     */
    @Override
    public void releaseSkuStockLock(List<OmsOrderItem> orderItemList){
        List<OmsOrderItem> result = new ArrayList<>();
        for(OmsOrderItem item : orderItemList){
            if (!item.getProductType().equals(1)) {
                //普通商品
                result.add(item);
            } else{
                //组合商品
                PmsCombinedProductExample example = new PmsCombinedProductExample();
                example.createCriteria().andParentIdEqualTo(item.getProductSkuId());
                //购买的组合商品的子商品集合
                List<PmsCombinedProduct> pmsCombinedProducts = pmsCombinedProductMapper.selectByExample(example);
                //子商品
                for (PmsCombinedProduct pmsCombinedProduct: pmsCombinedProducts) {
                    //每个子商品在组合商品中的数量
                    OmsOrderItem combined = new OmsOrderItem();
                    //子商品的skuId
                    combined.setProductSkuId(pmsCombinedProduct.getSkuStockId());
                    //子商品在该订单中的总数量=在组合商品中的数量*订单中的数量
                    combined.setProductQuantity(pmsCombinedProduct.getNum()*item.getProductQuantity());
                    result.add(combined);
                }
            }
        }
        if(!CollectionUtils.isEmpty(result)){
            portalOrderDao.releaseSkuStockLock(result);
        }
    }

    public static void main(String[] args) {
        String body = "草铵膦闲飞草胺磷果园茶园荒地牛筋草小飞蓬水花生杂草除草剂|二甲四氯钠除草剂玉米水稻小麦2甲4氯纳除草剂草坪防除阔叶30克|环嗪酮除树剂死树剂竹杂除灭杀大树王杀竹子剂除草烂根除杂草神剂";
        System.out.println(body);
        System.out.println(body.length());
        if(body.length()>30){
            body = body.substring(0,30);
        }
        System.out.println(body);

    }
}
